const eventEmiter = require('wy-EventEmiter');
const config = require('wy-Config');
const pomelo = require('wy-Pomelo');
//微信模块的功能调用
let isRecordding = false;
let autoStopTimer = null;
let recordFiles = [];  //所有需要播放的录音都先来这里存着，然后一个个播放
let isPlayRecord = false; //是否正在播放录音

let _playOneRecord = function () {
    if (recordFiles.length === 0) {
        isPlayRecord = false;
    } else {
        let wxAudio = wx.createInnerAudioContext();
        let recordFile = recordFiles.shift();
        wxAudio.src = config.readRecordRootUrl + recordFile.fileName;
        wxAudio.loop = false;
        wxAudio.onPlay(() => {
            cc.audioEngine.pauseAll();
            eventEmiter.emit('playRecordStart', recordFile);
        });
        wxAudio.onEnded(() => {
            if (recordFiles.length == 0) {
                cc.audioEngine.resumeAll();
            }
            eventEmiter.emit('playRecordEnd', recordFile);
            wxAudio.destroy();
            _playOneRecord();
        })
        wxAudio.play();
    }
}

let _playAllRecord = function () {
    if (isPlayRecord) {
        return;
    }
    if (recordFiles.length > 0) {
        isPlayRecord = true;
        _playOneRecord();
    }
}

let WeChat = {
    //微信自动登录
    login: function (cb) {
        let self = this;
        wx.login({
            success: function (res) {
                let imgWidth = cc.game.canvas.width / 720 * 175;
                let imgHeight = cc.game.canvas.height / 1280 * 65;
                let button = wx.createUserInfoButton({
                    type: 'image',
                    image: './res/raw-assets/d2/d22666d5-3816-4682-b951-e4a9877145fb.3e9fa.png',
                    // type:'text',
                    // text: '微信登陆',
                    style: {
                        left: cc.game.canvas.width / 4 - imgWidth / 2,
                        top: cc.game.canvas.height / 3 + imgHeight / 2,
                        width: imgWidth,
                        height: imgHeight
                        // lineHeight: 150,
                        // backgroundColor: '#ff0000',
                        // color: '#ffffff',
                        // textAlign: 'center',
                        // fontSize: 16,
                        // borderRadius: 4
                    },
                    withCredentials: true
                });
                button.onTap(function (data) {
                    self.getLocation(function (location) {
                        let obj = {
                            code: res.code,
                            encryptedData: data.encryptedData,
                            iv: data.iv,
                            signature: data.signature,
                            latitude: location.latitude,
                            longitude: location.longitude,
                        };
                        cb(obj);
                        button.destroy();
                    })
                });
                button.show();
                //wx.getUserInfo({
                //    success:function(data){
                //        self.getLocation(function(location){
                //            let obj={
                //                code:res.code,
                //                encryptedData:data.encryptedData,
                //                iv:data.iv,
                //                signature:data.signature,
                //                latitude:location.latitude,
                //                longitude:location.longitude,
                //            };
                //            cb(obj);
                //        });
                //    }
                //});
            }
        })
    },
    //获取地理位置  回掉函数中的res.latitude,res.longitude为经纬度
    getLocation: function (cb) {
        wx.getLocation({
            success: function (res) {
                cb(res);
            }
        });
    },
    //转发
    //开始录音
    startRecord: function (roomNo) {
        if (isRecordding) { return; }
        cc.log('开始录音');
        isRecordding = true;
        isPlayRecord = true;
        cc.audioEngine.pauseAll();
        //开启自动关闭录音定时器
        autoStopTimer = setTimeout(() => {
            WeChat.stopRecord();
        }, 10000);
        let RecorderManager = wx.getRecorderManager();
        RecorderManager.start({
            sampleRate: 12000,
            numberOfChannels: 1,
            encodeBitRate: 24000,
            format: 'mp3',
            frameSize: 10
        });
        RecorderManager.onStop(function (data) {
            cc.log('录音结束');
            isRecordding = false;
            isPlayRecord = false;
            _playAllRecord();
            cc.audioEngine.resumeAll();
            eventEmiter.emit('stopRecord');
            let tempFilePath = data.tempFilePath;
            //let fileSize=data.fileSize;
            //let duration=data.duration;
            let fileName = `${roomNo}_${new Date().getTime()}`;
            cc.log('开始上传录音', tempFilePath);
            wx.uploadFile({
                url: config.uploadRecordUrl,
                filePath: tempFilePath,
                name: fileName,
                formData: {
                    fileName: fileName + '.mp3'
                },
                success: function (res) {
                    cc.log('MP3文件上传成功', res);
                    //eventEmiter.emit('stopRecord',fileName);
                    pomelo.request('room.manager.broadcastRecord', { roomNo: roomNo, fileName: fileName + '.mp3' }, (data) => { });
                }
            });
        });
        eventEmiter.emit('startRecord');
    },
    //停止录音
    stopRecord: function () {
        if (!!autoStopTimer) {
            clearTimeout(autoStopTimer);
            autoStopTimer = null;
        }
        let RecorderManager = wx.getRecorderManager();
        RecorderManager.stop();
    },
    //播放网络录音
    playRecord: function (_id, fileName) {
        recordFiles.push({ _id: _id, fileName: fileName });
        _playAllRecord();
    },
    //分享
    share: function (title, queryObj, successCallBack, imageUrl = 'https://xlsocket.073c.com/image/share.png') {
        let query = Object.keys(queryObj).map(function (key) {
            return key + '=' + queryObj[key];
        }).join("&");
        wx.shareAppMessage({
            title: title,
            imageUrl: imageUrl,
            query: query,
            success: successCallBack
        })
    },
    //游戏退出
    exit: function () {
        wx.exitMiniProgram({});
    },
    //游戏截图
    screenshot: function (argObj, cb) {
        var canvas = cc.game.canvas;
        var width = cc.winSize.width;
        var height = cc.winSize.height;
        let obj = {
            x: 0,
            y: 0,
            width: width,
            height: height,
            destWidth: width,
            destHeight: height,
            success(res) {
                cb(res.tempFilePath);
            }
        };
        Object.assign(obj, argObj);
        canvas.toTempFilePath(obj);
    }
};

module.exports = WeChat;